<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>昆明呈贡周边导航</title>
    <style>
        body, html {
            margin: 0;
            height: 100%;
            font-family: "Segoe UI", "Helvetica Neue", sans-serif;
            background-color: #f5f5f5;
        }
        #container {
            height: 100%;
        }

        #panel {
            position: absolute;
            top: 20px;
            left: 20px;
            z-index: 999;
            background: white;
            border-radius: 10px;
            padding: 20px;
            width: 340px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        input[type="text"] {
            width: 100%;
            padding: 8px;
            font-size: 14px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 6px;
        }

        button {
            padding: 8px 12px;
            background-color: #0066cc;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            margin-top: 5px;
        }

        button:hover {
            background-color: #004c99;
        }

        .mode {
            display: inline-block;
            margin-right: 10px;
        }

        #results {
            max-height: 220px;
            overflow-y: auto;
            margin-top: 12px;
            border-top: 1px solid #eee;
            padding-top: 10px;
        }

        .result-item {
            padding: 8px;
            margin-bottom: 4px;
            border-radius: 5px;
            background-color: #f0f0f0;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .result-item:hover {
            background-color: #e0e0e0;
        }

        .highlight-info {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 8px;
        }
    </style>

    <script src="https://api.map.baidu.com/api?v=3.0&type=webgl&ak=F1HTcXXaXIlbjdwO8hoZKXgJp1ZnQVAe"></script>
</head>
<body>

<div id="panel">
    <label>我的地址：</label>
    <input id="start" type="text" placeholder="如 昆明南站">
    <button onclick="useCurrentLocation()">使用当前位置</button><br><br>

    <label>导航方式：</label><br>
    <label class="mode"><input type="radio" name="mode" value="walk" checked> 步行</label>
    <label class="mode"><input type="radio" name="mode" value="drive"> 驾车</label>
    <label class="mode"><input type="radio" name="mode" value="transit"> 公交</label><br><br>

    <label>搜索附近：</label>
    <input id="keyword" type="text" placeholder="如 酒店/餐厅/超市">
    <button onclick="searchNearby()">搜索</button>

    <div id="results"></div>
</div>

<div id="container"></div>

<script>
    const centerPoint = new BMapGL.Point(102.8414, 24.8897); // 昆明呈贡
    const map = new BMapGL.Map("container");
    map.centerAndZoom(centerPoint, 15);
    map.enableScrollWheelZoom(true);
    map.addControl(new BMapGL.ScaleControl());
    map.addControl(new BMapGL.ZoomControl());
    map.addControl(new BMapGL.CityListControl());

    let startPoint = null;

    const local = new BMapGL.LocalSearch(map, {
        renderOptions: { map: map },
        onSearchComplete: function(results) {
            const resultDiv = document.getElementById("results");
            resultDiv.innerHTML = "";
            if (local.getStatus() === BMAP_STATUS_SUCCESS) {
                for (let i = 0; i < results.getCurrentNumPois(); i++) {
                    const poi = results.getPoi(i);
                    const item = document.createElement("div");
                    item.className = "result-item";
                    item.textContent = poi.title + " - " + poi.address;
                    item.onclick = () => navigateTo(poi.point);
                    resultDiv.appendChild(item);
                }
            } else {
                resultDiv.innerHTML = "<div>未找到相关地点。</div>";
            }
        }
    });

    function searchNearby() {
        const keyword = document.getElementById("keyword").value;
        local.searchNearby(keyword, centerPoint);
    }

    function geocode(address) {
        return new Promise((resolve, reject) => {
            const geo = new BMapGL.Geocoder();
            geo.getPoint(address, function(point) {
                if (point) {
                    resolve(point);
                } else {
                    reject("无法解析地址: " + address);
                }
            });
        });
    }

    async function navigateTo(destPoint) {
        map.clearOverlays();
        if (!startPoint) {
            const addr = document.getElementById("start").value;
            try {
                startPoint = await geocode(addr);
            } catch (err) {
                alert(err);
                return;
            }
        }

        map.addOverlay(new BMapGL.Marker(startPoint));
        map.addOverlay(new BMapGL.Marker(destPoint));

        const mode = document.querySelector('input[name="mode"]:checked').value;
        let route;

        if (mode === "walk") {
            route = new BMapGL.WalkingRoute(map, {
                renderOptions: { map: map, autoViewport: true }
            });
        } else if (mode === "drive") {
            route = new BMapGL.DrivingRoute(map, {
                renderOptions: { map: map, autoViewport: true }
            });
        } else if (mode === "transit") {
            route = new BMapGL.TransitRoute(map, {
                renderOptions: { map: map, autoViewport: true }
            });
        }

        route.search(startPoint, destPoint);

        route.setSearchCompleteCallback(function(results) {
            if (route.getStatus() === BMAP_STATUS_SUCCESS) {
                const plan = results.getPlan(0);
                const duration = plan.getDuration(true);
                const distance = plan.getDistance(true);

                const resultDiv = document.getElementById("results");
                const info = document.createElement("div");
                info.className = "highlight-info";
                info.textContent = `预计用时：${duration} | 距离：${distance}`;
                resultDiv.insertBefore(info, resultDiv.firstChild);
            }
        });
    }

    function enableAutocomplete(id) {
        const ac = new BMapGL.Autocomplete({
            input: id,
            location: centerPoint
        });
        ac.addEventListener("onconfirm", function(e) {
            const _value = e.item.value;
            const fullAddr = _value.province + _value.city + _value.district + _value.street + _value.business;
            document.getElementById(id).value = fullAddr;
            startPoint = null;
        });
    }

    enableAutocomplete("start");

    function useCurrentLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(pos) {
                const lng = pos.coords.longitude;
                const lat = pos.coords.latitude;
                startPoint = new BMapGL.Point(lng, lat);
                document.getElementById("start").value = "我的当前位置";
                alert("当前位置设置成功，可点击搜索结果导航");
            }, function(err) {
                alert("定位失败：" + err.message);
            });
        } else {
            alert("浏览器不支持定位功能");
        }
    }
</script>
</body>
</html>